#!/usr/bin/env python
import os
import sys
from optparse import OptionParser

def getSettings():
  parser = OptionParser();
  parser.add_option("-i","--in",dest="infile",help="Input racecar format file.");
  parser.add_option("-n","",dest="resp",type="int",help="Class variable - must be integer in [0,1]");
  parser.add_option("-o","--out",dest="out",help="Output file. If not specified, defaults to stdout.");
  
  opts,args = parser.parse_args();

  if opts.out == None:
    opts.out = sys.stdout;
  else:
    opts.out = open(opts.out,"w")

  if opts.infile == None:
    raise ValueError, "Must specify input file.";
  else:
    opts.infile = open(opts.infile);

  if opts.resp == None:
    raise ValueError, "Must specify which variable is the class/response variable.";

  return opts;

def main():
  opts = getSettings();
  infile = opts.infile;
  out = opts.out;
  n = int(opts.resp);

  # Extract header - this shouldn't change. 
  header = infile.readline();
  cols = len(header.split());
  out.write(header);

  # Write the "d" line. 
  out.write( "\t".join(['d' for i in xrange(cols)]) );
  out.write("\n");

  # Write the class line. 
  cline = "";
  for i in xrange(cols):
    if i == n:
      cline += "class";
    else:
      cline += "";
    cline += "\t";
  print >> out, cline;

  # Now just copy the data over line by line. 
  for line in infile:
    out.write(line);

  infile.close();
  out.close();

if __name__ == "__main__":
  main();
